package com.qipay.api.common.controller.v1;

import com.alibaba.fastjson.JSONObject;
import com.qipay.pay.TradeService;
import com.qipay.pay.entity.CpTradeQueryRequest;
import com.qipay.scalar.type.ApiStatusEnum;
import com.qipay.utils.ResultUtils;
import com.qipay.utils.XmlUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/sig/v1")
public class TradeQueryController {

    @Value("${api.response.sign.name}")
    String apiResponseSignName;

    @Value("${api.response.key.name}")
    String apiResponseKeyName;

    @Autowired
    private TradeService tradeService;

    @RequestMapping(value = "/trade/query", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    private String tradeQuery(
            HttpServletRequest request,
            HttpServletResponse response
    ) throws Exception {
        Map<String, Object> params = (Map<String, Object>) request.getAttribute("params");
        String cpSecretId = (String) request.getAttribute("cpSecretId");
        CpTradeQueryRequest bean = (CpTradeQueryRequest) XmlUtils.mapToBean(params, CpTradeQueryRequest.class);
        bean.setCpSecretId(cpSecretId);
        Map<String, Object> result = tradeService.tradeQuery(bean);

        Assert.notNull(result,
                ResultUtils.buildErrorMsg(ApiStatusEnum.SERVICE_BUSY, ApiStatusEnum.SERVICE_BUSY.getInfo()));
        result = ResultUtils.signResult(result, cpSecretId,apiResponseSignName, apiResponseKeyName);
        return JSONObject.toJSONString(result);
    }
}

